package com.spark.gaea.utils;

import com.google.common.collect.Lists;
import com.spark.gaea.base.TreeVo;
import com.spark.gaea.base.Treeable;

import java.util.List;

public final class TreeUtil {
	public static List listToTree(final List list) {
		final TreeVo root = new TreeVo() {
			@Override
			public void setText(final String text) {
			}

			@Override
			public String getText() {
				return null;
			}
		};
		root.setId("0");
		return findChild(root, list);
	}

	public static List listToTree(final Treeable root, final List list) {
		return findChild(root, list);
	}

	private static List<Treeable> findChild(final Treeable root, final List<Treeable> allDatas) {
		final List<Treeable> children = Lists.newArrayList();
		final List<Treeable> notChildren = Lists.newArrayList();
		for (final Treeable vo : allDatas) {
			if (vo.getParentId().equals(root.getId())) {
				children.add(vo);
			} else {
				notChildren.add(vo);
			}
		}
		for (final Treeable child : children) {
			child.setChildren(findChild(child, notChildren));
			if (child.getChildren() == null || child.getChildren().size() < 1) {
				child.setLeaf(true);
			} else {
				child.setLeaf(false);
			}
		}
		return children;
	}
}
